package com.ss.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.ss.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class LoginUserDto implements UserDetails {

    private User user;

    private String jwtToken;

    private List<String> permissions;

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> result;

    public  LoginUserDto(User user){
        this.user = user;
    }

    public  LoginUserDto(User user, List<String> permissions){
        this.user = user;
        this.permissions = permissions;
    }

    public  LoginUserDto(){

    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(!CollectionUtils.isEmpty(permissions)){
            List<SimpleGrantedAuthority> list = new ArrayList<>();
            if(result==null) {
                result = permissions.stream()
                        .map(permission -> new SimpleGrantedAuthority(permission))
                        .collect(Collectors.toList());
            }
            return result;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
